// admin/system/dao/sys_dict_data_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysDictDataDao 字典数据访问接口
type SysDictDataDao interface {
	Create(dictData *model.SysDictData) error
	GetByID(id int64) (*model.SysDictData, error)
	Update(dictData *model.SysDictData) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysDictData, int64, error)
	ListByDictType(dictType string) ([]*model.SysDictData, error)
	ListByDictTypeAndStatus(dictType, status string) ([]*model.SysDictData, error)
}

type sysDictDataDao struct {
	db *gorm.DB
}

// NewSysDictDataDao 创建字典数据访问实例
func NewSysDictDataDao() SysDictDataDao {
	return &sysDictDataDao{
		db: database.GetDB(),
	}
}

func (d *sysDictDataDao) Create(dictData *model.SysDictData) error {
	logger.Info("创建字典数据", zap.Int64("dict_code", dictData.DictCode))
	return d.db.Create(dictData).Error
}

func (d *sysDictDataDao) GetByID(id int64) (*model.SysDictData, error) {
	logger.Debug("根据ID获取字典数据", zap.Int64("dict_code", id))
	var dictData model.SysDictData
	err := d.db.Where("dict_code = ? AND status = '0'", id).First(&dictData).Error
	return &dictData, err
}

func (d *sysDictDataDao) Update(dictData *model.SysDictData) error {
	logger.Info("更新字典数据", zap.Int64("dict_code", dictData.DictCode))
	return d.db.Save(dictData).Error
}

func (d *sysDictDataDao) Delete(id int64) error {
	logger.Info("删除字典数据", zap.Int64("dict_code", id))
	return d.db.Where("dict_code = ?", id).Delete(&model.SysDictData{}).Error
}

func (d *sysDictDataDao) List(page, pageSize int) ([]*model.SysDictData, int64, error) {
	logger.Debug("获取字典数据列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var dictData []*model.SysDictData
	var total int64

	offset := (page - 1) * pageSize
	db := d.db.Model(&model.SysDictData{}).Where("status = '0'")

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&dictData).Error; err != nil {
		return nil, 0, err
	}

	return dictData, total, nil
}

func (d *sysDictDataDao) ListByDictType(dictType string) ([]*model.SysDictData, error) {
	logger.Debug("根据字典类型获取字典数据列表", zap.String("dict_type", dictType))
	var dictData []*model.SysDictData
	err := d.db.Where("dict_type = ? AND status = '0'", dictType).Order("dict_sort").Find(&dictData).Error
	return dictData, err
}

func (d *sysDictDataDao) ListByDictTypeAndStatus(dictType, status string) ([]*model.SysDictData, error) {
	logger.Debug("根据字典类型和状态获取字典数据列表",
		zap.String("dict_type", dictType),
		zap.String("status", status))
	var dictData []*model.SysDictData
	err := d.db.Where("dict_type = ? AND status = ?", dictType, status).Order("dict_sort").Find(&dictData).Error
	return dictData, err
}
